<?php

namespace common\helpers;

use Yii;
/**
 * 公共的工具性方法.
 * User: paul
 * Date: 2017/1/4 0004
 * Time: 17:58
 */
class Helper
{

    /**
     * 生成不同时间间隔的sql区间，供mysql查询不同的时间间隔的数据
     * @param $type
     * @return string
     */
    public static function intervalDate($type) {
        switch ($type) {
            case 1: // 今天
                $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end = mktime(0, 0, 0, date('m'), date('d')+1, date('Y'))-1;
                break;
            case 3: // 本月
                $start = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $end = mktime(0, 0, 0, date('m')+1, 1, date('Y'))-1;
                break;
            case 4: // 本年
                $start = mktime(0, 0, 0, 1, 1, date('Y'));
                $end = mktime(0, 0, 0, 1, 1, date('Y')+1)-1;
                break;
            case 5: // 昨天
                $start = mktime(0, 0, 0, date('m'), date('d')-1, date('Y'));
                $end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                break;
            case 9: // 前七天
                $start = mktime(0, 0, 0, date('m'), date('d')-6, date('Y'));
                $end = mktime(date('H'), date('m'), date('s'), date('m'), date('d'), date('Y'));
                break;
            default:
                $start = ''; $end = '';
        }

        return " between $start and $end ";
    }

    /**
     * 查询指定日期的区间数据
     * @param string $date 时间
     * @param int $type 格式 1: 时间戳 2: Y-m-d 格式
     * @return string
     */
    public static function specialDate($date, $type = 1)
    {
        switch ($type) {
            case 1:
                $start = mktime(0, 0, 0, date('m', $date), date('d', $date), date('Y', $date));
                $end = mktime(0, 0, 0, date('m', $date), date('d', $date)+1, date('Y', $date))-1;
                break;
            case 2:
                list($year, $month, $day) = explode('-', $date);
                $start = mktime(0, 0, 0, $month, $day, $year);
                $end = mktime(0, 0, 0, $month, $day+1, $year)-1;
                break;
            default:
                $start = ''; $end = '';
        }

        return " BETWEEN $start AND $end ";
    }

    /**
     * 显示日期格式化
     * @param int $time 时间戳
     * @return false|string
     */
    public static function displayDate($time)
    {
        $today = date('Y-m-d');
        $mtToday = strtotime($today);
        $mtTomorrow = $mtToday + 24 * 3600;
        $tomorrow = date('Y-m-d', $mtTomorrow);

        $mtTime = date('Y-m-d', $time);

        if ($mtTime == $today) {
            $msg = '今天' . date('H:i', $time);
        } elseif ($mtTime == $tomorrow) {
            $msg = '明天' . date('H:i', $time);
        } else {
            $msg = date('d日H:i', $time);
        }
        return $msg;
    }

    /**
     * ---------------------------------------
     * 上传base64格式的图片
     * @param string $imgBase64 图片的base64编码
     * @param string $folder
     * @return mixed
     * ---------------------------------------
     */
    public static function uploadImage($imgBase64, $folder = 'image')
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgBase64, $result)){
            $type = $result[2];
            $type = $type == 'jpeg' ? 'jpg' : $type;
            $fileName = time() . rand( 1 , 1000 ) . "." . $type;
            /* 以年月创建目录 */
            $dir = date('Y-m-d', time());
            $path = Yii::$app->params['upload']['webPath'] . $folder . '/' . $dir;

            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }

            $fileName = $dir . '/' . $fileName;

            if (file_put_contents(dirname($path) . '/' . $fileName, base64_decode(str_replace($result[1], '', $imgBase64)))) {
                return $fileName;
            }
        }

        return false;
    }

    /**
     * ---------------------------------------
     * 生成 图片路径
     * @param string $url 图片相对路径，一般为“201605/1235654.jpg”
     * @param string $params 生成链接时的附加测试，例如长宽等
     * @param bool $isUrl 是否生成php文档形式的url
     * @param string $folder 图片保存的文件夹
     * @return string
     * ---------------------------------------
     */
    public static function src($url, $params = '', $isUrl = false, $folder = 'image')
    {
        if ($isUrl === false) {
            //完整圖片地址直接放回地址
            if(strpos($url,'http') !== false || strpos($url,'https') !== false){
                return $url;
            }

            $urlInfo = explode('/',$url);
            if($urlInfo && count($urlInfo) > 0){
                trim($urlInfo[0]) != trim($folder) && $url = $folder . '/' . $url;
            }
            unset($urlInfo);

            strpos($url, 'http') === false && $url = Yii::$app->params['upload']['webUrl'] . '/' . $url;
            return $url;
        }

        $query = 'path=' . $url;
        if ($params) {
            $query .= '&' . $params;
        }

        if (Yii::$app->params['storage_encrypt']) {
            $query = 'path=' . base64_encode($query);

        }

        return Yii::getAlias('@storageUrl') . '/index.php?' . $query;
    }

    /**
     * @desc 解析图片地址
     * @param string $imagePath 图片地址
     * @return array|string
     */
    public  function parseImage($imagePath)
    {
        if(is_array($imagePath) && !empty($imagePath)){
            $images = Picture::find()->where(['in','path',$imagePath])->select('id')->indexBy('id')->asArray()->all();
            return $images ?implode(',', array_keys($images)): [];
        }

        if(!empty($imagePath)){
            $image = Picture::find()->where((['path'=>$imagePath]))->select('id')->asArray()->all();
            return $image ? $image[0]['id'] : '';
        }
    }

    /**
     * 获取当前时间毫秒数
     * 该方法主要用于计算毫秒差
     * @return float
     */
    public static function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1) + floatval($t2)) * 1000);
    }

    /**
     * 格式毫秒时间
     * 保留2位毫秒
     * @param string $format
     * @param null $uTimeStamp
     * @return false|string
     */
    public static function formatUDate($uTimeStamp, $format = 'Y-m-d H:i:s.u') {
        $uTimeStamp = $uTimeStamp / 1000;
        $timestamp = floor($uTimeStamp);
        $milliseconds = round(($uTimeStamp - $timestamp) * 100);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }

    /**
     * 随机小数
     * @param float $min
     * @param float $max
     * @return float|int
     */
    public static function randFloat($min, $max){
        return $min + mt_rand()/mt_getrandmax() * ($max - $min);
    }

    /**
     * 过滤掉特殊字符，只保存大小写字母下划线和中文
     * @param $str
     * @param int $length
     * @return string
     */
    public static function filterString($str, $length = 20) {
        $rs = [];
        for($i = 0 ; $i < mb_strlen($str) ; $i++){
            if(count($rs) >= $length) break;
            $tmpChar = mb_substr($str,$i,1);
            if(preg_match('/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]+$/u',$tmpChar)) $rs[] = $tmpChar;
        }
        return empty($rs) ? '' : implode('', $rs);
    }

    /***
     * @param $start
     * @param $end
     * @return array
     * 获取时间段内每天的日期
     */
    public static function continuousDate($start,$end) {
        $days = ceil(($end-$start)/86400);
        $dayArr = [];
        for($day=0;$day<$days;$day++){
            $dayTime = $start+$day*86400;
            $dayArr[] = date("Y-m-d",$dayTime);
        }
        return $dayArr;
    }

}